﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Streaming_Service.FileTransfer {
    using System.IO;

    using Streaming_Service.Media;
    using Streaming_Service.SQL_Ting;

    public class FileTransferHelper {
        public static bool ReceiveUpload(UploadFileInfo fileInfo) {
            if(ProperUploadFileInfo(fileInfo)) {
                MediaFunc.EnsureTmpFolderExists();
                MediaFunc.CreateMovieFolder(fileInfo.MovieId);
                var tmpFilename = MediaFunc.GetTmpFolder() + DBFunc.MD5(fileInfo.Filename + DBFunc.Rand(1000, 100000) + Environment.TickCount);
                var localFS = new FileStream(tmpFilename, FileMode.Create, FileAccess.Write, FileShare.Write);
                var remoteS = fileInfo.FileByteStream;

                var buffer = new byte[65536];
                var read = 0;
                while((read = remoteS.Read(buffer,0, buffer.Length)) > 0) {
                    localFS.Write(buffer, 0, read);
                }
                remoteS.Close();
                localFS.Close();

                if(File.Exists(tmpFilename)) {
                    if (new FileInfo(tmpFilename).Length == fileInfo.Size) {
                        fileInfo.TmpFilename = tmpFilename;
                        return true;
                    }else {
                        File.SetAttributes(tmpFilename, FileAttributes.Normal);
                        File.Delete(tmpFilename);
                    }
                }
            }
            return false;
        }

        public static bool ProperUploadFileInfo(UploadFileInfo fileInfo) {
            if (fileInfo == null) return false;
            if(string.IsNullOrEmpty(fileInfo.Filename)) return false;
            if (fileInfo.Size < 1) return false;
            if (fileInfo.FileByteStream == null) return false;
            if (!fileInfo.FileByteStream.CanRead) return false;
            return true;
        }

        public static bool VerifyThumbFileExtension(UploadFileInfo fileInfo) {
            if(string.IsNullOrEmpty(fileInfo.Filename) || !fileInfo.Filename.Contains(".")) return false;
            var parts = fileInfo.Filename.Split('.');
            var ext = "." + parts[parts.Length - 1];
            return MediaFunc.thumbFileExtensions.Contains(ext);
        }

        public static bool VerifyMovieFileExtension(UploadFileInfo fileInfo) {
            if (string.IsNullOrEmpty(fileInfo.Filename) || !fileInfo.Filename.Contains(".")) return false;
            var parts = fileInfo.Filename.Split('.');
            var ext = "." + parts[parts.Length - 1];
            return MediaFunc.movieFileExtensions.Contains(ext);
        }
    }
}